package com.gitee.magic.converter;

import java.util.Properties;

import com.gitee.magic.core.converter.AbstractConverterEditor;
import com.gitee.magic.core.json.JsonObject;

/**
 * @author start
 */
public class PropertiesConverterEditor extends AbstractConverterEditor<String> {
	
	public PropertiesConverterEditor(Class<?> prototype) {
		super(prototype);
	}

	@Override
	public void restore(Object value) {
		if (value != null) {
			Class<?> target=value.getClass();
			JsonObject json;
			if(target.equals(JsonObject.class)) {
				json=(JsonObject)value;
			}else {
				json=new JsonObject(String.valueOf(value));
			}
			setSource(json);
			Properties prop=new Properties();
			for(String key:json.keySet()) {
				Object val=json.get(key);
				prop.put(key,val);
			}
			setValue(prop);
		}
	}

	@Override
	public String converter() {
		if (getValue() == null) {
			return null;
		}
		return String.valueOf(getSource());
	}

	@Override
	public Object getSource() {
		if (getValue() == null) {
			return null;
		}
		Properties prop = (Properties) getValue();
		JsonObject json = new JsonObject();
		for(Object key:prop.keySet()) {
			Object val=prop.get(key);
			json.put(String.valueOf(key), val);
		}
		return json;
	}

}